/**
 * 自定义事件
 */

let eventNumber = 0;  //事件编号

const eventInstanceMap = {};  //所有事件实例

export class DefineEvent{
    constructor(){
        eventNumber ++;
        this.number = eventNumber;
        this.eventMap = {};
        eventInstanceMap[eventNumber] = this;
    }
    on(key,fn){  //注册事件
        if(typeof fn !== 'function') return;
        this.eventMap[key] = this.eventMap[key] || [];
        this.eventMap[key].push(fn);
        return key;
    }
    emit(key,...params){  //触发事件
        if(!this.eventMap[key]) return;
        this.eventMap[key].forEach(e => {
            e(...params);
        });
        return key;
    }
    delete(key,fn){
        const eventList = this.eventMap[key];
        if(!eventList) return;
        eventList.splice(
            eventList.indexOf(fn),
            1,
        );
    }
    destroy(){
        delete eventInstanceMap[this.number]; 
    }
    has(key){
        return !!this.eventMap[key];
    }
    get(key){
        return this.eventMap[key];
    }
}

/**
 * 根据编号获取事件实例
 * @param {*} number 
 */
export function getEventInstance(number){
    return eventInstanceMap[number];
}

/**
 * 销毁实例
 * @param {*} number 
 */
export function destroyEventInstance(number){
    delete eventInstanceMap[number]; 
}